extends Node
  # 加载 JSON 文件


# 全局存储的JSON数据
var characters_global: Array = []       # 角色数据
var skills_global: Array = []           # 技能数据
var formations_global: Array = []       # 阵法数据
var save_data_global: Dictionary = {}   # 存档数据
var mods_global: Array = []

func _ready():
	# 游戏启动时加载所有JSON数据
	init()
	
func init() -> void:
	save_data_global = load_from_file("res://data/save.json")
	var gamedata = load_from_file("res://data/data.json")
	characters_global = gamedata.characters
	skills_global = gamedata.skills
	formations_global = gamedata.formations
	print(characters_global.size(),skills_global.size(),formations_global.size())

func save_to_file(content):
	var file = FileAccess.open("res://data/save.json", FileAccess.WRITE)
	file.store_string(content)

func load_from_file(url):
	var file = FileAccess.open(url, FileAccess.READ)
	var content = file.get_as_text()
	file.close()
	var json =  JSON.parse_string(content)
	return json
	
func getFormatItemById(target_id):
	for obj in formations_global:
		# 检查对象是否包含 id 属性，且与目标 id 匹配
		if "id" in obj and obj.id == target_id:
			return obj
	return null  # 未找到时返回 null

func getModItemById(target_id):
	for obj in mods_global:
		# 检查对象是否包含 id 属性，且与目标 id 匹配
		if "id" in obj and obj.id == target_id:
			return obj
	return null  # 未找到时返回 null

func getSkillItemById(target_id):
	for obj in skills_global:
		# 检查对象是否包含 id 属性，且与目标 id 匹配
		if "id" in obj and obj.id == target_id:
			return obj
	return null  # 未找到时返回 null


func getRoleItemById(target_id):
	for obj in characters_global:
		# 检查对象是否包含 id 属性，且与目标 id 匹配
		if "id" in obj and obj.id == target_id:
			return obj
	return null  # 未找到时返回 null

func getMyRoleItemById(target_id):
	for obj in save_data_global.owned_characters:
		# 检查对象是否包含 id 属性，且与目标 id 匹配
		if "rel_id" in obj and obj.rel_id == target_id:
			return obj
	return null  # 未找到时返回 null
